<template>
  <div class="monitoringControl">
    <div class="header">
      <el-form
        :inline="true"
        :model="formInline"
        size="small"
        label-width="70px"
      >
        <el-form-item label="设备类型">
          <el-select
            v-model="formInline.type"
            placeholder="请选择设备类型"
            @change="onChange($event, 'type')"
            filterable
            clearable
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号">
          <el-select
            v-model="formInline.version"
            placeholder="请选择设备型号"
            @change="onChange($event, 'version')"
            filterable
            clearable
          >
            <el-option
              v-for="item in equipmentModel"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="add"
            >添加监控模板</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="success" size="small" @click="configuration"
            >监控管理配置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="content">
      <div class="mainOut" :style="{ height: height + 'px !important' }">
        <div class="mainInner">
          <div class="card-box">
            <el-card
              class="card"
              :body-style="{ padding: '0px' }"
              v-for="(item, index) in tableData"
              :key="index"
              shadow="never"
            >
              <div slot="header">
                <el-tooltip
                  class="item"
                  effect="light"
                  :content="item.type_name"
                  placement="top-start"
                >
                  <div class="name">
                    <img
                      src="../../assets/images/device.png"
                      alt
                      class="icon"
                    />
                    <div class="label">
                      设备类型:{{ item.type_name | ellipsis }}
                    </div>
                  </div>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  effect="light"
                  :content="item.modle_name"
                  placement="top-start"
                >
                  <div class="name">
                    <img
                      src="../../assets/images/device.png"
                      alt
                      class="icon"
                    />
                    <div class="label">
                      设备型号:{{ item.modle_name | ellipsis }}
                    </div>
                  </div>
                </el-tooltip>
              </div>
              <div class="card-content">
                <div
                  class="name"
                  v-for="(self, idx) in temperature"
                  v-if="item.id === self.templateId"
                  :key="idx"
                >
                  <span class="iconfont iconview"></span>
                  <div class="label">
                    {{ self.name }}
                    ({{ self.min + self.unit }}
                    {{
                      !self.max || self.max === "" || self.max === null
                        ? ""
                        : "±" + self.max + self.unit
                    }})
                  </div>
                </div>
              </div>
              <div class="bottom-clearfix">
                <el-button type="success" plain size="mini" @click="edit(item)"
                  >编辑</el-button
                >
                <el-button type="warning" plain size="mini" @click="view(item)"
                  >查看</el-button
                >
                <el-button type="danger" plain size="mini" @click="del(item)"
                  >删除</el-button
                >
              </div>
            </el-card>
          </div>
        </div>
      </div>
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>
    <el-drawer
      @close="resetForm('ruleForm')"
      :title="
        type === 'add'
          ? '添加监控模板'
          : type === 'edit'
          ? '编辑监控模板'
          : '查看监控模板'
      "
      size="480px"
      custom-class="custom-drawer"
      :visible.sync="visible"
    >
      <el-form
        size="small"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="el-drawer-ruleForm"
      >
        <!-- <el-form-item label="公司名称:" prop="companyId">
          <el-select
            v-model="ruleForm.companyId"
            clearable
            placeholder="请选择公司名称"
            class="formItem"
            @change="handlercompanyId"
          >
            <el-option
              v-for="item in companySelList"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="设备类型" prop="type">
          <el-select
            :disabled="disabled"
            class="formItem"
            v-model="ruleForm.type"
            placeholder="请选择设备类型"
            filterable
            clearable
            @change="handlerType"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备型号" prop="version">
          <el-select
            :disabled="disabled"
            class="formItem"
            v-model="ruleForm.version"
            placeholder="请选择设备型号"
            filterable
            clearable
          >
            <el-option
              v-for="item in equipmentModel"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备监控项" prop="monitor">
          <el-select
            :disabled="slider"
            class="formItem"
            v-model="ruleForm.monitor"
            placeholder="请选择设备监控项(可多选)"
            multiple
            filterable
            clearable
          >
            <el-option
              v-for="item in monitorList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-for="item in monitorList"
          :key="item.id"
          v-if="ruleForm.monitor.indexOf(item.id) > -1"
          label-width="0px"
        >
          <div style="display: flex; align-items: center; width: 100%">
            <span class="monitor-name">{{ item.name }}</span>
            <div class="monitor-slider">
              <span class="temperature">上下限阈值 ({{ min }}~{{ max }})</span>
              <el-slider
                :disabled="slider"
                @input="onChangeSlider($event, item)"
                style="width: 100%"
                v-model="item.temperature"
                range
                :min="min"
                :max="max"
              ></el-slider>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div class="el-drawer__footer">
        <el-button
          :disabled="slider"
          type="primary"
          @click.prevent="submitForm('ruleForm')"
          :loading="confirmLoading"
          >{{ confirmLoading ? "保 存 中..." : "保 存" }}</el-button
        >
        <el-button :disabled="slider" @click="resetForm('ruleForm')"
          >取 消</el-button
        >
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  getMonitorList,
  devicTypeList,
  devicModelList,
  monitorAdd,
  monitorEdit,
  monitorFind,
  deviceMonitorList,
  companySel,
  monitorDelete
} from "../../utils/api";
import { mapState, mapGetters } from "vuex";
//监控管理设置
export default {
  name: "MonitoringControl",
  props: ["height"],
  data() {
    return {
      slider: false,
      disabled: false,
      errImg: 'this.src="' + require("../../assets/images/chest.png") + '"',
      formInline: {
        type: "", //设备类型
        version: "" //设备型号
      },
      versionList: [], //设备型号列表
      typeList: [], //设备类型列表
      monitorList: [], //设备监控项
      tableData: [], //表格数据
      temperature: [], //温度列表
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      total: 0, //总条数
      currentPage: 1, //当前页
      pageSize: 10, //每页条数
      tooltip: true,
      visible: false,
      confirmLoading: false, //按钮加载
      type: "add",
      ruleForm: {
        companyId: "", //公司id
        version: "", //设备型号
        type: "", //设备类型
        monitor: [], //设备监控项
        temperature: [] //上下阈值
      },
      rules: {
        version: [
          { required: true, message: "请输入设备型号", trigger: "change" }
        ],
        type: [
          { required: true, message: "请选择设备类型", trigger: "change" }
        ],
        monitor: [
          { required: true, message: "请选择设备监控项", trigger: "change" }
        ]
      },
      userInfo: {}, //用户信息
      currentRow: {}, //当前行信息
      min: -500,
      max: 500,
      // 公司的列表
      companySelList: [],
      equipmentModel: []
    };
  },
  created() {
    this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
    this.getDataInit();
  },
  // 当文字大于6的时候添加省略号
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 6) {
        return value.slice(0, 6) + "...";
      }
      return value;
    }
  },
  computed: {
    ...mapState(["org_id"])
  },
  watch: {
    org_id(val) {
      this.currentPage = 1;
      this.getInit();
    }
  },
  methods: {
    getDataInit() {
      if (this.org_id === "" || this.org_id === null || !this.org_id) {
      } else {
        this.getInit();
      }
    },
    async getInit() {
      await this.getSelect();
      await this.getData();
    },
    //下拉框改变事件
    onChange(value, key) {
      this.formInline[key] = value;
      this.currentPage = 1;
      this.getData();
    },
    //获取搜索下拉列表事件
    async getSelect() {
      this.typeList = await this.postRequest(devicTypeList, {
        companyId: this.org_id
      }).then(res => res.data); //设备类型列表
      this.equipmentModel = await this.postRequest(devicModelList, {
        companyId: this.org_id
      }).then(res => res.data); //设备型号
      this.monitorList = await this.postRequest(deviceMonitorList, {
        companyId: this.org_id
      }).then(res => res.data); //设备监控项
      this.monitorList.forEach(v => {
        v.temperature = [0, 10];
      });
    },
    getData() {
      const params = {
        pageSize: this.pageSize,
        pageNumber: this.currentPage,
        typeId: this.formInline.type, //设备类型
        modelId: this.formInline.version, //设备型号
        companyId: this.org_id
      };
      this.postRequest(getMonitorList, params).then(res => {
        if (res.code === 200) {
          this.total = res.data.template.count;
          this.tableData = res.data.template.data;
          this.temperature = res.data.threshold;
        }
      });
    },
    handlerType(val) {
      // 根据选择的类型id匹配对应的类型名字
      let obj = {};
      obj = this.typeList.find(item => {
        return item.id === val; //筛选出匹配数据
      });
      // this.logoutForm.typeName = obj.name;
      this.postRequest(devicModelList, { companyId: this.org_id }).then(res => {
        let newarr = [];
        res.data.map(v => {
          if (val == v.deviceTypeId) {
            newarr.push(v);
          }
        });
        this.equipmentModel = newarr;
      });
    },
    //分页
    handleSizeChange(val) {
      //每页条数
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前第几页
      this.currentPage = val;
      this.getData();
    },
    //添加
    add() {
      this.visible = true;
      this.disabled = false;
      this.slider = false;
      this.type = "add";
    },
    //编辑
    edit(row) {
      this.currentRow = row;
      this.type = "edit";
      this.disabled = true;
      this.slider = false;
      this.detail(row);
    },
    detail(row) {
      this.visible = true;
      this.postRequest(monitorFind, { id: row.id }).then(res => {
        const list = JSON.parse(JSON.stringify(this.monitorList));
        res.data.monitor.forEach(item => {
          const arr = [item.min, item.max];
          const index = list.map(v => v.id).indexOf(item.monitorId);
          if (index > -1) list[index].temperature = arr;
        });
        this.monitorList = list;

        this.ruleForm = {
          version: res.data.data[0].modelId, //设备型号
          type: res.data.data[0].typeId, //设备类型
          monitor: res.data.monitor.map(v => v.monitorId) //设备监控项
        };
        // console.log(this.ruleForm);
      });
    },
    //查看
    view(row) {
      this.currentRow = row;
      this.disabled = true;
      this.slider = true;
      this.type = "view";
      this.detail(row);
    },
    // 删除
    del(row) {
      this.$confirm("您确定删除此模版吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.postRequest(monitorDelete, { monitorId: row.id }).then(res => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getData();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    onChangeSlider(val, row) {
      const list = JSON.parse(JSON.stringify(this.monitorList));
      const index = list.map(v => v.id).indexOf(row.id);
      if (index > -1) list[index].temperature = val;
      this.monitorList = list;
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const arr = [];
          this.monitorList.forEach(item => {
            const index = this.ruleForm.monitor.indexOf(item.id);
            if (index > -1) {
              arr.push({
                monitorId: item.id,
                min: item.temperature[0],
                max: item.temperature[1]
              });
            }
          });
          const params = {
            companyId: this.org_id, //公司id
            user_id: this.userInfo.id,
            modelId: this.ruleForm.version, //设备型号
            typeId: this.ruleForm.type, //设备类型
            parameter: JSON.stringify(arr)
          };
          const url = this.type === "add" ? monitorAdd : monitorEdit;
          if (this.type === "edit") params.id = this.currentRow.id;
          this.confirmLoading = true;
          this.postRequest(url, params)
            .then(res => {
              this.confirmLoading = false;
              if (res.code === 200) {
                this.resetForm(formName);
                this.getInit();
              }
            })
            .catch(err => {
              this.confirmLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.visible = false;
    },
    // 点击监控管理配置
    configuration() {
      this.$router.push("/Configuration");
    }
    //  获取公司的无分页列表
    // getcompanySel() {
    //   this.postRequest(companySel).then(res => {
    //     if (res.code == 200) {
    //       this.companySelList = res.data;
    //     }
    //   });
    // },
    //  拿到公司的id
    // handlercompanyId(val) {
    //   this.ruleForm.companyId = val;
    // }
  }
};
</script>

<style scoped>
.monitor-name {
  width: 100px;
  text-align: right;
  vertical-align: middle;
  box-sizing: border-box;
  color: #606266;
  font-size: 14px;
  padding-right: 12px;
}

.monitor-slider {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: calc(100% - 100px);
}

.mainOut {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.mainInner {
  overflow-y: auto;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 20px;
  box-sizing: border-box;
}

.card-box {
  display: flex;
  flex-wrap: wrap;
}

.bottom-clearfix {
  padding: 10px 20px;
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #ebeef5;
  background: white;
  position: relative;
  z-index: 1;
}

.card {
  width: 240px;
  margin-right: 20px;
  margin-bottom: 20px;
}

.card-content {
  min-height: 130px;
  padding: 20px;
}

.temperature {
  color: #9ea0a5;
  font-size: 12px;
  text-align: center;
}

.formItem {
  width: 100%;
}

.header >>> .el-form-item {
  margin-bottom: 0;
}

.header {
  padding: 20px 30px;
  border: 1px solid #eaedf3;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  width: 97%;
  margin: 0 auto;
}

.content {
  padding: 30px;
  box-sizing: border-box;
}

.img {
  width: 90px;
  height: 60px;
  border-radius: 4px;
}

/*设备名称*/
.content {
  padding-right: 20px;
  overflow: hidden;
  width: 100%;
}

.card {
  /*width: min-content;*/
}

.name {
  display: flex;
  align-items: center;
  height: 24px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.iconview {
  font-size: 14px;
  color: #0077f8;
  margin-right: 10px;
}

.icon {
  width: 16px;
  height: 16px;
  margin-right: 10px;
}

.label {
  height: 24px;
  line-height: 24px;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #606266;
  color: rgba(62, 63, 66, 1);
  margin-bottom: 10px;
}

.label:last-of-type {
  margin-bottom: 0;
}
.el-drawer__footer {
  position: sticky;
  bottom: 0;
}
</style>
